<template>
  <div class="login-container">
    <el-card class="login-card">
      <div class="login-header">
        <img src="../assets/logo.png" alt="Logo" class="login-logo">
        <h2>高校教师绩效系统</h2>
      </div>
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="0" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" prefix-icon="User" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" prefix-icon="Lock" type="password" placeholder="密码" @keyup.enter="handleLogin"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin">登录</el-button>
        </el-form-item>
        <div class="login-options">
          <el-button type="text" @click="goToRegister">立即注册</el-button>
          <el-button type="text">忘记密码?</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import axios from 'axios'  // 修改为直接使用axios

const router = useRouter()
const userStore = useUserStore()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        // 修改请求方式，使用URLSearchParams格式发送表单数据
        const params = new URLSearchParams();
        params.append('username', loginForm.username);
        params.append('password', loginForm.password);
        
        const response = await axios.post('http://localhost:8081/api/user/login', params, {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        });
        
        // 检查响应状态
        if (response.data.code === 200) {
          const { token, user } = response.data.data
          
          // 存储用户信息和token
          userStore.setToken(token)
          userStore.setUser(user)
          userStore.setUserRole(user.role)
          
          ElMessage.success('登录成功')
          router.push('/')
        } else {
          // 显示后端返回的错误信息
          ElMessage.error(response.data.msg || '登录失败')
        }
      } catch (error) {
        // 处理网络错误或后端返回的错误
        if (error.response && error.response.data) {
          ElMessage.error(error.response.data.msg || '登录失败')
        } else {
          ElMessage.error('登录失败，请检查网络连接')
        }
        console.error('登录错误:', error)
      } finally {
        loading.value = false
      }
    }
  })
}

const goToRegister = () => {
  router.push("/register")
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  padding: 20px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-logo {
  width: 80px;
  height: 80px;
  margin-bottom: 10px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
}

.login-options {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>